package com.token.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.token.bean.Jin;
import com.token.bean.User;
import com.token.bean.layuiBean.ResultPage;
import com.token.bean.layuiBean.VoPage;
import com.token.service.JinService;
import com.token.service.UserService;
import com.token.util.DateUtils;
import com.token.util.Respons.ResponseUtil;
import com.token.util.sms.EhcacheUtil;
import io.swagger.models.auth.In;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 用户注册表 前端控制器
 * </p>
 *
 * @author 冯政尚
 * @since 2019-07-30
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    JinService jinService;

    /**
     * @return 查询所有
     */
    @RequestMapping(value = "selectUser", method = RequestMethod.GET)
    @ResponseBody
    public List selectUser() {
        return userService.list();
    }


    @RequestMapping(value = "userLogin.html", method = RequestMethod.GET)
    public String login() {
        return "userLogin";
    }

    @RequestMapping(value = "userLoginTo.html", method = RequestMethod.GET)
    public String userLoginTo() {
        return "userLoginTo";
    }

    @RequestMapping(value = "userLoginResult.html", method = RequestMethod.GET)
    public String userLoginResult(String tel,Model model) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("tel",tel);
        User user = userService.getOne(wrapper);
        model.addAttribute("receipt",user.getReceipt());
        return "userLoginResult";
    }

    @RequestMapping(value = "jin.html", method = RequestMethod.GET)
    public String jin() {
        return "jin";
    }

    @RequestMapping(value = "jin_add.html", method = RequestMethod.GET)
    public String jin_add() {
        return "jin_add";
    }

    @RequestMapping(value = "selectMyPage", method = RequestMethod.GET)
    @ResponseBody
    public ResultPage<User> selectMyPage(VoPage voPage, String status) {
        return userService.selectMyPage(voPage, status);
    }

    /**
     * @param voPage
     * @return 禁用管理列表查询
     */
    @RequestMapping(value = "selectByStatus", method = RequestMethod.GET)
    @ResponseBody
    public ResultPage<Jin> selectByStatus(VoPage voPage) {
        return userService.selectByStatus(voPage);
    }

    /**
     * @param tel   手机号
     * @param token 令牌
     * @return 申请
     */
    @RequestMapping(value = "/land")
    @ResponseBody
    public Map land(String tel, String token,String token2) {
        Map map = new HashMap();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("token", token);
        User user = userService.getOne(wrapper);
        if (user == null) {
            map.put("msg", "令牌1不存在");
            return map;
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("token2",token2);
        User userToken2 = userService.getOne(queryWrapper);
        if(userToken2==null){
            map.put("msg","令牌2不存在");
            return map;
        }
        wrapper.eq("tel", tel);
        User oneUser = userService.getOne(wrapper);
        if (oneUser != null) {
            String s = userService.SendSMSO(tel, oneUser.getExtractionCode());
            map.put("msg", s);
            return map;
        }
        List<User> uu = userService.list();
        for (int i = 0; i < uu.size(); i++) {
            if (uu.get(i).getTel() != null && uu.get(i).getTel().equals(tel)) {
                map.put("msg", "该令牌已失效");
                return map;
            }
            List<Jin> jinList = jinService.list();
            for (int j = 0; j < jinList.size(); j++) {
                if (jinList.get(j).getTel().equals(tel.substring(0, 3))) {
                    map.put("msg", "该" + tel.substring(0, 3) + "开头手机号被禁用");
                    return map;
                }
            }
        }
        if (user != null) {
            QueryWrapper wr = new QueryWrapper();
            wr.eq("token", token);
            wr.eq("status", "已绑定");
            User u = userService.getOne(wr);
            if (u != null) {
                map.put("msg", "该令牌已失效");
                return map;
            } else {
                QueryWrapper wrapper1 = new QueryWrapper();
                wrapper1.eq("token", token);
                wrapper1.eq("token2", token2);
                User user1 = userService.getOne(wrapper1);

                if (user1.getReceipt() == null) {
                    map.put("msg", "令牌不存在");
                    return map;
                }
                if (user1.getTel() == null) {
                    String time = "2";
                    String s = userService.SendSMSO(tel, user1.getExtractionCode());
                    if (s.equals("提交失败")) {
                        map.put("msg", s);
                        return map;
                    }
                    User user2 = new User();
                    user2.setTel(tel);
                    user2.setId(user1.getId());
                    user2.setStatus("已绑定");
                    if (!userService.updateById(user2)) {
                        map.put("msg", "提交失败");
                        return map;
                    }
                    map.put("msg", s);
                    return map;
                }

            }


        }
        return map;
    }

    /**
     * @param tel            手机号
     * @param extractionCode 令牌
     * @return 提取
     */
    @RequestMapping(value = "/loginResult")
    @ResponseBody
    public Map loginResult(String tel, String extractionCode) {
        Map map = new HashMap();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("extraction_code", extractionCode);
        wrapper.eq("tel", tel);
        User user = userService.getOne(wrapper);
        if (user == null) {
            map.put("msg", "手机号和提取码不匹配");
            return map;
        }
        return map;
    }

    @RequestMapping(value = "add.html", method = RequestMethod.GET)
    public String add() {
        return "add";
    }

    /**
     * @param user
     * @return 删除
     */
    @RequestMapping(value = "deleteById", method = RequestMethod.POST)
    @ResponseBody
    public Map deleteById(@RequestBody User user) {
        if (userService.removeById(user)) {
            return ResponseUtil.getSuccessMap();
        }
        return ResponseUtil.getExceptionMap();
    }

    @RequestMapping(value = "edit.html", method = RequestMethod.GET)
    public String edit(Model model, Long id) {
        model.addAttribute("id", id);
        return "edit";
    }

    /**
     * @param user
     * @return 编辑
     */
    @RequestMapping(value = "updateById", method = RequestMethod.POST)
    @ResponseBody
    public Map updateById(@RequestBody User user) {
        user.setUpdateTime(System.currentTimeMillis());
        if (userService.updateById(user)) {
            return ResponseUtil.getSuccessMap();
        }
        return ResponseUtil.getExceptionMap();
    }

    /**
     * @param user
     * @return 添加
     */
    @RequestMapping(value = "saveUser", method = RequestMethod.POST)
    @ResponseBody
    public  Map saveUser(@RequestBody User user) {

        for (int i = 0; i < user.getTokenNumber(); i++) {
            System.out.println("i:"+i);
            user.setCreateTime(System.currentTimeMillis());
            user.setToken2(getToken());
            user.setStatus("未绑定");
            user.setTelStatus(1);
            user.setExtractionCode(getStringRandom(6));
            user.setToken(getStringRandom(12));
            if (!userService.save(user)) {
                return ResponseUtil.getExceptionMap();
            }
            user.setId(null);
        }
        return ResponseUtil.getSuccessMap();
    }


    //token2
    public  String getToken(){
        Integer mm = null;
        List ss = new ArrayList();
        List<User> list = userService.list();
        if (list.size() == 0) {
            return "000001";
        }
        for (int j = 0; j < list.size(); j++) {
            ss.add(Integer.valueOf(list.get(j).getToken2()));
        }
        //最大值
        Integer max = (Integer) Collections.max(ss);
        mm = max + 1;
        String s = "00000" + mm;
        return s.substring(s.length() - 6);

    }




    //生成随机数字和字母,
    public String getStringRandom(int length) {
        String val = "";
        Random random = new Random();
        //length为几位密码
        for(int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if( "char".equalsIgnoreCase(charOrNum) ) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char)(random.nextInt(26) + temp);
            } else if( "num".equalsIgnoreCase(charOrNum) ) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }


    /**
     * @param id
     * @return 解绑
     */
    @RequestMapping(value = "prohibit", method = RequestMethod.POST)
    @ResponseBody
    public Map prohibit(Long id) {
        User user = userService.getById(id);
        String phone = user.getTel();
        if (phone == null) {
            return ResponseUtil.RequestException("该记录未绑定手机号");
        } else {
            if (userService.updateTel(id) > 0) {
                return ResponseUtil.getSuccessMap();
            }
        }
        return ResponseUtil.getExceptionMap();

//        String str = phone.substring(0, 3);


    }

//        User user =  userService.getById(id);
//        String phone = user.getTel();
//        if(phone==null){
//            return ResponseUtil.RequestException("该记录未绑定手机号");
//        }else{
//            String str =  phone.substring(0,3);
//            if(userService.updateTel(str)>0){
//                return ResponseUtil.getSuccessMap();
//            }
//        }
//        return ResponseUtil.getExceptionMap();
//    }

    @RequestMapping(value = "updateByTelStatus", method = RequestMethod.POST)
    @ResponseBody
    public Map updateByTelStatus(String telStatus) {


        if (userService.updateByTelStatus(telStatus) > 0) {
            return ResponseUtil.getSuccessMap();
        }

//        User user1 = new User();
//        System.out.println("123:"+user1.getSs());
//        if(telStatus!=user1.getSs()){
//        return ResponseUtil.RequestException("没有该号段");
//        }else{
//            if(userService.updateByTelStatus(telStatus)>0){
//                return ResponseUtil.getSuccessMap();
//            }
//        }
//        if(userService.updateByTelStatus(telStatus)>0){
//            return ResponseUtil.getSuccessMap();
//        }

        return ResponseUtil.getExceptionMap();

    }

//    @RequestMapping(value = "qi", method = RequestMethod.POST)
//    @ResponseBody
//    public Map qi(String telStatus) {
//        if (userService.qi(telStatus) > 0) {
//            return ResponseUtil.getSuccessMap();
//        }
//        return ResponseUtil.getExceptionMap();
//
//    }

    @RequestMapping(value = "qi", method = RequestMethod.POST)
    @ResponseBody
    public Map qi(@RequestBody Jin jin) {
        if (jinService.removeById(jin)) {
            return ResponseUtil.getSuccessMap();
        }
        return ResponseUtil.getExceptionMap();

    }


    /**
     * @return 添加禁用手机号开头
     */
    @RequestMapping(value = "insertTel", method = RequestMethod.POST)
    @ResponseBody
    public Map insertTel(@RequestBody Jin jin) {
        jin.setCreateTime(System.currentTimeMillis());
        if (jinService.save(jin)) {
            return ResponseUtil.getSuccessMap();
        }
        return ResponseUtil.getExceptionMap();

    }
//    @RequestMapping(value = "insertTel", method = RequestMethod.POST)
//    @ResponseBody
//    public Map selectTel(String tel) {
//        Map map = new HashMap();
//        List<User> userList = userService.list();
//        Set<String> set = new HashSet();
//        for (int i = 0; i < userList.size(); i++) {
//
//            if (userList.get(i).getTel() != null && userList.get(i).getTel().substring(0, 3).equals(tel)) {
//                set.add(userList.get(i).getTel().substring(0, 3));
//            }
//
//        }
//        if (set.size() == 0) {
//            map.put("msg", tel + "不能使用" + tel + "开头的手机号");
//            return map;
//        }
//        for (int i = 0; i < userList.size(); i++) {
//            if (userList.get(i).getTel() != null && userList.get(i).getTel().substring(0, 3).equals(tel)) {
//                if (userList.get(i).getTelStatus().equals(2)) {
//                    map.put("msg", "不能使用" + tel + "开头的手机号");
//                    return map;
//                }
//
//                User user = new User();
//                user.setId(userList.get(i).getId());
//                user.setTelStatus(2);
//                if (!userService.updateById(user)) {
//                    map.put("msg", "禁用失败");
//                    return map;
//                }
//            }
//
//        }
//        map.put("msg", "禁用成功");
//        return map;
//
//    }


    /**
     * @param response
     * @param status
     * @throws IOException 导出
     */
    @RequestMapping("/createExcel")
    public void createExcel(HttpServletResponse response, String status) throws IOException {

        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        //建立新的sheet对象（excel的表单）
        HSSFSheet sheet = wb.createSheet("成绩表");
        //在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
        HSSFRow row1 = sheet.createRow(0);
        //创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
        HSSFCell cell = row1.createCell(0);
        //设置单元格内容
        cell.setCellValue("信息表");
        //合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
        //在sheet里创建第二行
        HSSFRow row2 = sheet.createRow(1);
        //创建单元格并设置单元格内容
        row2.createCell(0).setCellValue("序号");
        row2.createCell(1).setCellValue("令牌1");
        row2.createCell(2).setCellValue("令牌2");
        row2.createCell(3).setCellValue("手机号");
        row2.createCell(4).setCellValue("回执");
        row2.createCell(5).setCellValue("手机号是否绑定");
        row2.createCell(6).setCellValue("手机号是否禁用");
        row2.createCell(7).setCellValue("创建时间");
        row2.createCell(8).setCellValue("修改时间");
        row2.createCell(9).setCellValue("备注");
        //在sheet里创建第三行
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("status", status);
        List<User> user = userService.list(wrapper);
        System.out.println("list:"+user);
        for (int i = 0; i < user.size(); i++) {
            if (user.get(i).getCreateTime() != null) {
                user.get(i).setCreateTimes(DateUtils.getDate(user.get(i).getCreateTime()));
            }
            if (user.get(i).getUpdateTime() != null) {
                user.get(i).setUpdateTimes(DateUtils.getDate(user.get(i).getUpdateTime()));
            }
            HSSFRow row3 = sheet.createRow(2 + i);
            row3.createCell(0).setCellValue(i + 1);
            row3.createCell(1).setCellValue(user.get(i).getToken());
            row3.createCell(2).setCellValue(user.get(i).getToken2());
            row3.createCell(3).setCellValue(user.get(i).getTel());
            row3.createCell(4).setCellValue(user.get(i).getReceipt());
            row3.createCell(5).setCellValue(user.get(i).getStatus());
            if (user.get(i).getTelStatus() == 1) {
                row3.createCell(6).setCellValue("启用");
            } else {
                row3.createCell(6).setCellValue("禁用");
            }
            row3.createCell(7).setCellValue(user.get(i).getCreateTimes());
            row3.createCell(8).setCellValue(user.get(i).getUpdateTimes());
            row3.createCell(9).setCellValue(user.get(i).getRemarks());

        }

        //输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=details.xls");
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
    }






}
